from flask import Flask, request, jsonify  # 修正Flask导入（首字母大写）
import pandas as pd
from itertools import combinations  # 修正拼写错误iteretools→itertools
app = Flask(__name__)  # 修正Flask初始化（首字母大写）
# 加载模型
frequent_itemsets = pd.read_pickle('./frequent_itemsets.pkl')
rules = pd.read_pickle('./rules.pkl')

@app.route('/recommend', methods=['POST'])  # 修正methods参数格式（去掉多余引号）
def recommend():
    # 接收传过来的参数
    data = request.json.get('items', [])  # 补充缺失的右括号

    # 生成关联规则推荐
    recommendations = []  # 修正变量名recommendbations→recommendations
    for idx, rule in rules.iterrows():
        antecedents = list(rule['antecedents'])
        consequents = list(rule['consequents'])
        # 检查规则前件是否跟输入匹配
        if set(antecedents).issubset(set(data)):
            recommendations.extend(consequents)  # 修正缩进
    # 去重并返回结果
    recommendations = list(set(recommendations) - set(data))  # 修正变量名
    return jsonify({"recommendations": recommendations})  # 修正变量名和key名

if __name__ == "__main__":
    app.run()
    